﻿using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshCollider))]
public class HCHexagon : MonoBehaviour {


	private float _radius = 1f;
	
	private float _width = 0f;
	private float _segment = 0f;
	private float _height = 0f;
	private float _apothem = 0f;
	
	public static float CalcSegment( float _r )
	{
		return 1.5f * _r;
	}
	
	public static float CalcHeight(float _r)
	{
		return Mathf.Sqrt( 3f ) * _r;
	}
	
	public static float CalcWidth(float _r)
	{
		return 2f * _r;
	}
	
	public float Radius
	{
		get{ return _radius; }
		set{ _radius = value; }
	}
	
	public void Build()
	{
		// create hexagon polygon
		Vector3[] _vertices = new Vector3[6];
		int[] _triangles = new int[12]{ 0,1,5, 5,1,2, 5,2,4,  4,2,3 };
		Vector3[] _normals = new Vector3[6];
		Vector2[] _uvs = new Vector2[6];
		
		float _angle = 0.0f;
		float _radAngle = _angle;
		
		for( int v = 0; v < 6; v++ )
		{
			_angle = (6-v) * 60.0f;
			_radAngle = Mathf.Deg2Rad * _angle;
			float _c = Mathf.Cos( _radAngle );
			float _s = Mathf.Sin( _radAngle );
			_uvs[v] = new Vector2( (1.0f + _c) * 0.5f, (1.0f + _s) * 0.5f );
			_vertices[v] = new Vector3( Mathf.Cos( _radAngle ) * _radius , 0.0f, Mathf.Sin( _radAngle ) * _radius );
			_normals[v] = Vector3.up;
		}
		
		Mesh _mesh = new Mesh();
		_mesh.name = "Hexagon";
		_mesh.vertices = _vertices;
		_mesh.normals = _normals;
		_mesh.triangles = _triangles;
		_mesh.uv = _uvs;
		
		MeshFilter _mf = GetComponent<MeshFilter>();
		_mf.mesh = _mesh;
		
	}
	
	void Start()
	{
		_width = 2f * _radius;
		_segment = 1.5f * _radius;
		_height = Mathf.Sqrt( 3f ) * _radius;
		_apothem = Mathf.Sqrt( 3f / 4f ) * _radius;
		
		Build ();
	}
	
	public bool Move( Vector3 _position )
	{
		transform.position = _position;
		return true;
	}
}
